package com.rbac.admin.controller;

import com.rbac.admin.common.Result;
import com.rbac.admin.model.dto.LoginDTO;
import com.rbac.admin.model.dto.RegisterDTO;
import com.rbac.admin.model.vo.LoginVO;
import com.rbac.admin.model.vo.UserVO;
import com.rbac.admin.service.SysUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 认证控制器
 */
@Tag(name="认证控制器", description = "认证控制器")
@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired
    private SysUserService userService;

    /**
     * 用户登录
     * @param loginDTO 登录参数
     * @return 登录结果
     */
    @Operation(summary = "用户登录")
    @PostMapping("/login")
    public Result<LoginVO> login(@Validated @RequestBody LoginDTO loginDTO) {
        LoginVO loginVO = userService.login(loginDTO);
        return Result.success(loginVO);
    }

    /**
     * 用户注册
     * @param registerDTO 注册参数
     * @return 注册结果
     */
    @Operation(summary = "用户注册")
    @PostMapping("/register")
    public Result<UserVO> register(@Validated @RequestBody RegisterDTO registerDTO) {
        UserVO userVO = userService.register(registerDTO);
        return Result.success(userVO);
    }
    
    /**
     * 用户登出
     * @return 登出结果
     */

    @Operation(summary = "用户登出")
    @GetMapping("/logout")
    public Result<String> logout() {
        // 获取当前认证信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated()) {
            // 清除Spring Security上下文
            SecurityContextHolder.clearContext();
            
            // 如果使用了Redis缓存，可以在这里清除用户的缓存信息
            // 获取当前用户信息
            Object principal = authentication.getPrincipal();
            if (principal instanceof UserDetails) {
                String username = ((UserDetails) principal).getUsername();
                // 清除用户相关缓存
                userService.clearUserCache(username);
            }
        }
        
        return Result.success("登出成功");
    }
}